Skip to main content

Reverse Words in a Given String (gfg)

Problem Description​

Given a string S, you need to reverse the order of words in the string. Words are separated by dots.

Examples​

Example 1:

Input: S = "i.like.this.program.very.much"
Output: "much.very.program.this.like.i"
Explanation: After reversing the words, the new string is "much.very.program.this.like.i".

Example 2:

Input: S = "pqr.mno"
Output: "mno.pqr"
Explanation: After reversing the words, the new string is "mno.pqr".

Your Task​

You don't need to read input or print anything. Your task is to complete the function reverseWords() which takes the string S as input and returns the string with the words reversed.

Expected Time Complexity: O(∣S∣)O(|S|)

Expected Auxiliary Space: O(∣S∣)O(|S|)

Constraints​

  • 1 ≤ |S| ≤ 2000

Problem Explanation​

The problem is to reverse the order of words in a string where words are separated by dots.

Code Implementation​

Written by @arunimad6yuq
class Solution:
def reverseWords(self, S):
# Split the string by dots
words = S.split('.')
# Reverse the list of words
words.reverse()
# Join the reversed list back into a string with dots
return '.'.join(words)

# Example usage
if __name__ == "__main__":
solution = Solution()
print(solution.reverseWords("i.like.this.program.very.much")) # Expected output: "much.very.program.this.like.i"
print(solution.reverseWords("pqr.mno")) # Expected output: "mno.pqr"

Example Walkthrough​

For the string S = "i.like.this.program.very.much":

  1. Split the string by dots into ["i", "like", "this", "program", "very", "much"].
  2. Reverse the list to ["much", "very", "program", "this", "like", "i"].
  3. Join the reversed list with dots to get "much.very.program.this.like.i".

For the string S = "pqr.mno":

  1. Split the string by dots into ["pqr", "mno"].
  2. Reverse the list to ["mno", "pqr"].
  3. Join the reversed list with dots to get "mno.pqr".

Solution Logic:​

  1. Split the string into words using the dot as a delimiter.
  2. Reverse the list of words.
  3. Join the reversed list back into a string with dots.

Time Complexity​

  • The time complexity is O(∣S∣)O(|S|), where |S| is the length of the input string.

Space Complexity​

  • The auxiliary space complexity is O(∣S∣)O(|S|) due to the storage required for the list of words.

References​